package com.zb.util;

import java.text.SimpleDateFormat;
import java.util.Date;

public class serialGenerater
{

	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
	public static Date previous_generate_time;//年月日时分秒
	public static int s_no = 0;//年月日时分秒

	public synchronized static String generateSerialNo()
	{
		String time_str;
		Date now = new Date();
		time_str = sdf.format(now);
		//如果previous_generate_time为空，则自动生成流水号
		if (previous_generate_time == null)
		{
			previous_generate_time = now;
			s_no++;
			return time_str + "0001";
		}
		//如果previous_generate_time与now 在年月日时分秒上相等， 则s_no++;
		if ((previous_generate_time.getTime() / 1000) == (now.getTime() / 1000))
		{
			int now_s_no = s_no + 1;
			s_no++;
			if (now_s_no < 10000)
			{
				return time_str + String.format("%04d", now_s_no);// String.valueOf(now_s_no);
			}
			else
			{
				try
				{
					Thread.sleep(1000);//睡一秒
				}
				catch (InterruptedException e)
				{
					;
				}
				s_no = 1;
				previous_generate_time = new Date();
				time_str = sdf.format(previous_generate_time);
				return time_str + "0001";
			}
		}
		else
		{
			previous_generate_time = now;
			s_no = 1;
			return time_str + "0001";
		}
	}
	
	/**
	 * 使用场景:1.x协议报文头下发流水号,预约流水号等
	 * @return
	 */
	public synchronized static String generateSerialNo14() {
		String time_str = null;
		Date now = new Date();
		time_str = sdf.format(now);
		// 如果previous_generate_time为空,则自动生成流水号
		if (previous_generate_time == null) {
			previous_generate_time = now;
			s_no++;
			return time_str.concat("01").substring(2);
		}
		// 如果previous_generate_time与now 在年月日时分秒上相等, 则s_no++;
		if ((previous_generate_time.getTime() / 1000) == (now.getTime() / 1000)) {
			int now_s_no = s_no + 1;
			s_no++;
			if (now_s_no < 10000) {
				return time_str.concat(String.format("%02d", now_s_no)).substring(2);
			} else {
				try {
					Thread.sleep(1000); // 睡一秒
				} catch (InterruptedException e) {
					;
				}
				s_no = 1;
				previous_generate_time = new Date();
				time_str = sdf.format(previous_generate_time);
				return time_str.concat("01").substring(2);
			}
		} else {
			previous_generate_time = now;
			s_no = 1;
			return time_str.concat("01").substring(2);
		}
	}

	public static void main(String[] args)
	{
		System.out.println(generateSerialNo14());
//		Sync sy = new Sync();
//		for (int i = 0; i < 10000; i++)
//		{
//			if (i == 5000)
//			{
//				try
//				{
//					Thread.sleep(1000);
//				}
//				catch (InterruptedException e)
//				{
//					
//					e.printStackTrace();
//				}
//			}
//			//			serialGenerater ge =  new serialGenerater();
//			new Thread(sy).start();
//		}

	}

}
